#! /bin/bash

# 获取环境变量
PLAY_HOME=/opt/playground

function installMaxwell()
{
 #在frames.txt中查看是否需要安装maxwell
 maxwellInfo=`egrep "maxwell" $PLAY_HOME/frames.txt`
 
 maxwell=`echo $maxwellInfo | cut -d " " -f1`
 isInstall=`echo $maxwellInfo | cut -d " " -f2`
 maxwellNode=`echo $maxwellInfo | cut -d " " -f3`
 node=`hostname`
 
 #是否在当前节点进行安装
 if [[ $isInstall = "true" && $maxwellNode = $node ]];then
     
     #查看$PLAY_HOME/frames目录下是否有maxwell安装包
     maxwellIsExists=`find $PLAY_HOME/frames -name $maxwell`
    
     if [[ ${#maxwellIsExists} -ne 0 ]];then
           
          if [[ ! -d /opt/app ]];then
              mkdir /opt/app && chmod -R 775 /opt/app
          fi
   
          #删除旧的
          maxwell_home_old=`find /opt/app -maxdepth 1 -name "*maxwell*"`
          for i in $maxwell_home_old;do
                rm -rf $i
          done

          #解压到指定文件夹/opt/app中
          echo "开始解压maxwell安装包"
          tar -zxvf $maxwellIsExists -C /opt/app >& /dev/null
          echo "maxwell安装包解压完毕"

          maxwell_home=`find /opt/app -maxdepth 1 -name "*maxwell*"`

          #配置 config.properties 文件
          cp $PLAY_HOME/biz_conf/maxwell/config.properties $maxwell_home/config.properties
          
          #拷贝Mysql连接驱动
          mysqlDrive=`egrep "^mysql-drive" $PLAY_HOME/configs.txt | cut -d " " -f2`
          lib_home="$PLAY_HOME/frames/lib"
          #判断驱动是否存在
          driveIsExists=`find $lib_home -name $mysqlDrive`
          if [[ ${#driveIsExists} -ne 0 ]];then
            cp $lib_home/$mysqlDrive $maxwell_home/lib/
          else
            echo "$lib_home目录下没有Mysql驱动"
          fi

          #配置 MAXWELL_HOME
          profile=/etc/profile.d/my_env.sh
          sudo sed -i "/^export MAXWELL_HOME/d" $profile
          echo "export MAXWELL_HOME=$maxwell_home" | sudo tee -a $profile

          #配置PATH
          sudo sed -i "/^export PATH=\$PATH:\$MAXWELL_HOME\/bin/d" $profile
          echo "export PATH=\$PATH:\$MAXWELL_HOME/bin" | sudo tee -a $profile

          #更新/etc/profile文件
          source /etc/profile && echo "更新/etc/profile环境变量完成"

          # 输出提示信息
          echo "-----------------------------"
          echo "|   Maxwell在$node安装成功！  |"
          echo "-----------------------------"
     else
         echo "$PLAY_HOME/frames目录下没有maxwell安装包"
     fi
 else
     echo "maxwell不允许被安装在当前节点"
 fi
}

installMaxwell
